#-*- coding:gb2312 -*-
#$Id: auth.py 33094 2008-09-09 02:10:05Z jorwen@NETEASE.COM $


def _u2s(var):
	if type(var) == unicode:
		return var.encode('gb18030')
	return var


def urs_auth(username, password, userip=""):
	URS_PRODUCT = "gamesales"
	URS_CHECK_OK = 200

	import urllib, md5
	passmd5 = md5.md5(password).hexdigest()
	uri_str = urllib.urlencode([('username',_u2s(username)), ('password',passmd5), \
		('product', URS_PRODUCT), ('type', 0), ('userip', userip)])
	url = "http://reg.163.com/services/userlogin?%s"

	fp = urllib.urlopen(url%uri_str)
	if not fp :
		return None

	ret = fp.readlines()
	code = int(ret[0].strip())
	return code == URS_CHECK_OK


def img_auth(imgname, word):
	from v4a.models import ImageValidate
	return ImageValidate.objects.validate_ok(imgname, word)	


def auth(request, verify_type):

	from v4a.models import Vote
	d = request.POST
	if verify_type == Vote.URS_AUTH:
		return (urs_auth(d['username'], d['password']), Vote.URS_AUTH)

	elif verify_type in (Vote.IMG_AUTH, Vote.EX1_AUTH):
		return (img_auth(d['imgname'], d['word']), Vote.IMG_AUTH)

	elif verify_type == Vote.EX2_AUTH:
		if not urs_auth(d['username'], d['password']):
			return (False, Vote.URS_AUTH)
		else:
			return (img_auth(d['imgname'], d['word']), Vote.IMG_AUTH)

	return (True, verify_type) 


def get_username(request, verify_type):
	from v4a.models import Vote
	if verify_type in (Vote.URS_AUTH, Vote.EX2_AUTH):
		return request.POST.get('username', '')

	return ''


def already_vote(request, vote):
	from v4a.models import VotesLog
	from datetime import datetime, timedelta
	filters = {'vote__id': vote.id}

	if vote.verify_type in (vote.NO_AUTH, vote.IMG_AUTH):
		return False

	if vote.verify_type in (vote.IP_AUTH, vote.EX1_AUTH):
		filters['ip'] = request.META['REMOTE_ADDR']

	if vote.verify_type in (vote.URS_AUTH, vote.EX2_AUTH):
		filters['user'] = request.POST['username']

	filters['time__gt'] = datetime.now() - timedelta(seconds=vote.keep_verify_time * 60)
	objects = VotesLog.objects.filter(**filters)

	return len(objects) > 0

